package com.itheima.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.common.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自定义元数据对象处理器，用于公共字段填充
 *
 * @author zhengbinghua
 * @since 2022/10/16 15:12
 */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
    /**
     * 插入操作，自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());
        // 以下每个字段都加入get set判断，避免某些表只有create相关字段，没有update相关字段时出现异常
        if (metaObject.hasGetter("createTime")) {
            metaObject.setValue("createTime", new Date());
        }
        if (metaObject.hasGetter("updateTime")) {
            metaObject.setValue("updateTime", new Date());
        }
        if (metaObject.hasGetter("createUser")) {
            metaObject.setValue("createUser", BaseContext.getCurrentId());
        }
        if (metaObject.hasGetter("updateUser")) {
            metaObject.setValue("updateUser", BaseContext.getCurrentId());
        }
        if (metaObject.hasGetter("userId")) {
            metaObject.setValue("userId", BaseContext.getCurrentId());
        }
        if (metaObject.hasGetter("orderTime")) {
            metaObject.setValue("orderTime", new Date());
        }
    }

    /**
     * 更新操作，自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());
        if (metaObject.hasGetter("updateTime")) {
            metaObject.setValue("updateTime", new Date());
        }
        if (metaObject.hasGetter("updateUser")) {
            metaObject.setValue("updateUser", BaseContext.getCurrentId());
        }
    }
}
